let http = require('http');
let fs = require('fs');
let archiver = require('archiver');
let child_process = require('child_process');
let querystring = require('querystring');

//1.打开authorize https://github.com/login/oauth/authorize
child_process.exec(`start https://github.com/login/oauth/authorize?client_id=Iv1.f8d020e613db0d43`);
//3.创建server，接受token，后点击发布

http.createServer((request, response) => {
    if (request.url !== '/favicon.ico') {
        let query = querystring.parse(request.url.match(/^\/\?([\s\S]+)$/)[1]);
        publish(query.token);
    }

    response.end();
}).listen(8082);

function publish(token) {
    let request = http.request({
        hostname: '127.0.0.1',
        port: 8081,
        path: `/publish?token=${token}`,
        method: 'POST',
        headers: {
            'Content-Type': 'application/octet-stream',
        },
    }, response => {
        console.log(response);
    });

    const archive = archiver('zip', {
        zlib: { level: 9 },
    });

    archive.directory('./sample/', false);

    archive.finalize();

    archive.pipe(request);
}

// fs.stat('./sample.html', (err, stats) => {
    /*
    let request = http.request({
        hostname: '127.0.0.1',
        port: 8081,
        method: 'POST',
        headers: {
            'Content-Type': 'application/octet-stream',
            // 'Content-Length': stats.size,
        },
    }, response => {
        console.log(response);
    });
    
    // 创建可读流
    // let file = fs.createReadStream('./sample.html');

    const archive = archiver('zip', {
        zlib: { level: 9 },
    });

    archive.directory('./sample/', false);

    archive.finalize();

    archive.pipe(request);
    
    // 将可读流写入到可写流
    // file.pipe(request);
    
    // file.on('end', () => {
    //     request.end();
    // });
    */
// });



// file.on('data', chunk => {
//     console.log(chunk.toString());
//     request.write(chunk);
// });

// file.on('end', chunk => {
//     console.log('read finished');
//     request.end(chunk);
// });
